package com.sjq.common.util;

import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ResourceBundle;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPClientConfig;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;

public class FTPClientHelper {


	//FTP客户端
    private FTPClient ftpClient;
    private ResourceBundle res=null;
    
    /**
     * 
     * 连接FTP服务器
     * @param remotePath //设定当前需要操作的目录
     * @return
     */
    
    public FTPClientHelper(String remotePath){
    	res = ResourceBundle.getBundle("FtpConfig");
    	try{
    		ftpClient=new FTPClient();
    		ftpClient.connect(res.getString("ftp.url"),21);//FTP服务器IP地址
    		ftpClient.login(res.getString("ftp.username"), res.getString("ftp.password"));//FTP服务器用户名和密码
    		ftpClient.setDataTimeout(1200000);
    		ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
    		//确定编码格式，否则不能正确下载中文文件
    		ftpClient.setControlEncoding("GBK");
    		FTPClientConfig conf=new FTPClientConfig(FTPClientConfig.SYST_NT);
    		conf.setServerLanguageCode("zh");
    		System.out.println("Login success!");
    		int reply=ftpClient.getReplyCode();
    		if(!FTPReply.isPositiveCompletion(reply)){
    			ftpClient.disconnect();
    			ftpClient=null;
    		}
    		//转移到设置的目录下
    		if(remotePath!=null&&!remotePath.equals("")){
    			String[] paths = remotePath.split("\\\\");
    			String path="\\";
    			for(int i=1; i<paths.length; i++){
    				path = path + paths[i] + "\\";
    				if(!ftpClient.changeWorkingDirectory(path)){
						ftpClient.makeDirectory(path);
	    			}
    			}
    			ftpClient.changeWorkingDirectory(remotePath);
    			System.out.println("file success!");
    		}
    	}catch(Exception e){
    		e.printStackTrace();
    	}
    }

    /**
     * 
     * 上传文件
     * @param remoteFile
     * @param localFile
     * @return String localFile
     */
    
    public boolean upload(String localFile,String filename){
    	boolean bool=false;
    	if(ftpClient!=null){
    		try{
    			File file=new File(localFile);
    			FileInputStream is=new FileInputStream(file);
    			bool = ftpClient.storeFile(new String(filename.getBytes("GBK"), "ISO-8859-1"), is);
    			is.close();
    			ftpClient.logout();
    		}catch(Exception e){
    			e.printStackTrace();
    			System.out.println("上传文件失败!请检查系统FTP设置,并确认FTP服务启动!");
    		}finally{
    			closeConnect();
    		}
    	}
    	return bool;

    }
    
    /**
     * 上传
     * @param is
     * @param filename
     * @return
     */
    public boolean upload(InputStream is,String filename){
    	boolean bool=false;
    	if(ftpClient!=null){
    		try{
    			bool = ftpClient.storeFile(new String(filename.getBytes("GBK"), "ISO-8859-1"), is);
    			is.close();
    			//ftpClient.logout();
    		}catch(Exception e){
    			e.printStackTrace();
    			System.out.println("上传文件失败!请检查系统FTP设置,并确认FTP服务启动!");
    		}finally{
    			closeConnect();
    		}
    	}
    	return bool;

    }
    
    /**
     * 上传
     * @param data
     * @param filename
     * @return
     */
    public boolean upload(byte[] data, String filename){
    	boolean bool=false;
    	if(ftpClient!=null){
    		try{
    			ByteArrayInputStream bis=null;
    			bis=new ByteArrayInputStream(data);
    			bool = ftpClient.storeFile(new String(filename.getBytes("GBK"), "ISO-8859-1"), bis);
    			bis.close();
    			ftpClient.logout();
    		}catch(Exception e){
    			e.printStackTrace();
    			System.out.println("上传文件失败!请检查系统FTP设置,并确认FTP服务启动!");
    		}finally{
    			closeConnect();
    		}
    	}
    	return bool;

    }
    
	/**
	 * 
	 * 下载文件至指定目录
	 * @param remoteFile 远程文件路径(服务器端)
	 * @param fileName 需要下载的文件名
	 * @param localPath 本地文件路径(客户端)
	 */
    
    public boolean download(String fileName,String localPath){
    	boolean bool=false;
    	if(ftpClient!=null){
    		try{
    			//ftpClient.changeWorkingDirectory(remoteFile);//转移到FTP服务器目录
    			FTPFile[] files=ftpClient.listFiles();
    			
    			for(FTPFile file:files){
    				if(file.getName().equals(fileName)){
    					System.out.println("---start---"+System.currentTimeMillis());
    					String path=localPath+"\\"+file.getName();
    					System.out.println(path);
    					File localFile=new File(path);
    					OutputStream ops=new FileOutputStream(localFile);
    					ftpClient.retrieveFile(file.getName(), ops);
    					ops.close();
    					System.out.println("---end---"+System.currentTimeMillis());
    					bool=true;
    					break;
    				}
    			}
    			
    		}catch(Exception e){
    			e.printStackTrace();
    			System.out.println("下载文件失败!请检查系统FTP设置,并确认FTP服务启动!");
    		}finally{
    			closeConnect();
    		}
    		
    	}
    	return bool;
    	
    }
    
    /**
     * 
     * 删除文件至FTP通用方法
     * @param fileName
     * @return
     */
    
    public boolean deleteFileFtp(String fileName){
    	boolean bool=false;
    	if(ftpClient!=null){
    		try{
    			bool=ftpClient.deleteFile(new String(fileName.getBytes("GBK"), "ISO-8859-1"));
    		}catch(Exception e){
    			e.printStackTrace();
    			System.out.println("删除文件失败!请确定文件是否存在!");
    		}finally{
    			closeConnect();//关闭FTP连接
    		}
    	}
    	return bool;
    }
    
    public boolean deleteAllFileFtp(){
    	boolean bool=false;
    	if(ftpClient!=null){
    		try{
    			bool=true;
    			FTPFile[] fs=ftpClient.listFiles();
				for(FTPFile ff:fs){
					bool=ftpClient.deleteFile(new String(ff.getName().getBytes("GBK"), "ISO-8859-1"));
				}
    		}catch(Exception e){
    			e.printStackTrace();
    			System.out.println("删除文件失败!请确定文件是否存在!");
    		}finally{
    			closeConnect();//关闭FTP连接
    		}
    		
    	}
    	return bool;
    }
	
	/**
	 * 
	 * 以流的形式下载文件
	 * @param remotePath
	 * @param fileName
	 * @return
	 */
    
	public byte[] downFileByte(String remotePath,String fileName){
        
		byte[] return_arraybyte=null;
		
		if(ftpClient!=null){
			try{
				FTPFile[] fs=ftpClient.listFiles();
				for(FTPFile ff:fs){
					if(ff.getName().equals(fileName)){
						InputStream ins=ftpClient.retrieveFileStream(ff.getName());
						ByteArrayOutputStream byteOut=new ByteArrayOutputStream();
						byte[] buf=new byte[204800];
						int bufsize=0;
						while((bufsize=ins.read(buf,0,buf.length))!=-1){
							byteOut.write(buf,0,bufsize);
						}
						return_arraybyte=byteOut.toByteArray();
						byteOut.close();
						ins.close();
						break;
					}
				}
						
				
			}catch(Exception e){
				e.printStackTrace();
			}finally{
				closeConnect();
			}
		
		}
		return return_arraybyte;
	}
	
	/**
	 * 
	 * 以流的形式下载文件
	 * @param remotePath
	 * @param fileName
	 * @return
	 */
	public boolean downFileToWeb(String remotePath,String fileName, String realFilePath){
		boolean bool = false;
		if(ftpClient!=null){
			try{
				FTPFile[] fs=ftpClient.listFiles();
				for(FTPFile ff:fs){
					if(ff.getName().equals(fileName)){
						File savePath = new File(realFilePath);
						if (savePath != null && !savePath.exists()) {
							savePath.mkdirs();
						}
						String file = realFilePath + "\\" + fileName;
						System.out.println("begin======"+file);
						InputStream ins=ftpClient.retrieveFileStream(new String(ff.getName().getBytes("GBK"), "ISO-8859-1"));
						BufferedOutputStream out1 = new BufferedOutputStream(new FileOutputStream(file));
						byte[] buf=new byte[204800];
						int bufsize=0;
						while((bufsize=ins.read(buf,0,buf.length))!=-1){
							out1.write(buf,0,bufsize);
						}
						out1.close();
						ins.close();
						System.out.println("end======"+file);
						break;
					}
				}
				ftpClient.getReply();
				bool = true;
			}catch(Exception e){
				e.printStackTrace();
			}finally{
				closeConnect();
			}
		}
		return bool;
	}
	
	/**
	 * 关闭FTP连接
	 */
	
	public void closeConnect(){
		try{
			ftpClient.disconnect();
		}catch(Exception e){
			e.printStackTrace();
		}
		
	}

}
